#ifndef FASTBUFFERMANAGER_H
#define FASTBUFFERMANAGER_H
#include <QAtomicInteger>
#include <QList>
#include <QMutex>
#include <QVector>
#include <QWaitCondition>

class FastBufferHandler;

class FastBufferManager
{
public:
  FastBufferManager();
  /// @brief 创建快速缓存队列
  /// @param bufferSize 单个缓存大小
  /// @param  bufferCount 缓存列表大小
  void createFastBufferList(int bufferSize, int bufferCount);
  /// @brief 获取缓存操作句柄
  /// @param id 缓存id
  /// @return 缓存句柄
  FastBufferHandler *bufferHandler(int id);
  /// @brief 描述收发关系，句柄[receiverId]将从句柄[senderId]读取数据
  /// @param senderId
  /// @param receiverId
  /// @return 连接是否成功
  bool connect(int senderId, int receiverId);
  /// @brief 标记一个缓存区
  /// @param id 缓存区id
  /// @param isMarked 缓存区是否可获取，拥有者是否放弃权限
  void markBuffer(int id, bool isMarked);
  /// @brief 标记一个缓存区
  /// @param id 缓存区id
  /// @param isReady 缓存区就绪，但拥有者还未放弃权限
  void markBufferReady(int id, bool isReady);

  /// @brief 设置超时时间单位：纳秒
  /// @param timeoutValue
  void setTimeout(int timeoutValue);
  /// @brief 记录超时次数
  /// @param ns
  void recordTimeout(long long ns);
  /// @brief 获取超时次数
  /// @return
  int timeoutCount() { return m_timeoutCount; };
  /// @brief 输出时间计数日志
  void printTimeCountLog();

private:
  /// @brief 获取缓存
  /// @param id
  /// @return
  QVector<double> &fastBuffer(int id);

  /// @brief 等待缓存状态
  /// @param waitMask
  void waitBufferReady(unsigned long waitMask);

  /// @brief 获取缓存就绪掩膜
  /// @return
  unsigned long readyMask() { return m_bufferReadyMask; }

  /// @brief 等待读取缓存区
  /// @param id
  void readyToRead(int id);
  /// @brief 等待写入缓存区
  /// @param id
  void readyToWrite(int id);

private:
  int m_bufferSize;
  int m_bufferCount;
  unsigned long m_bufferReadyMask;     // 缓存就绪掩膜
  QAtomicInteger<int> m_bufferIsReady; // 缓存就绪标志
  QAtomicInteger<int> m_timeoutValue;
  QAtomicInteger<int> m_timeoutCount;

  QWaitCondition m_waitCondition;
  QAtomicInteger<unsigned long> m_bufferReadyFlag;  // 标识各个buffer的数据生成就绪状态，但此时未解除占用
  QAtomicInteger<unsigned long> m_bufferOccupyFlag; // 标识各个buffer的占用状态,1表示未被写入者占用，可读
  QList<QVector<double>> m_bufferList;
  QList<FastBufferHandler *> m_bufferHandlerList;
  QVector<int> m_sendMap; // 数据发送关系映射，key：句柄id，value：读取的buffer索引

  friend class FastBufferHandler;
};

#endif // FASTBUFFERMANAGER_H
